% v20: fixing reprojection BUG
% v40: use 4 points homography -> remove 'degenerate' bug
% v50: change model structure to set of segments
function y = homography(model,H)

%         degenThres = 1e-10; 
        % BUG: at INIT step, real measurements to pixel's (90 -> hundreds)
        %      at this step, big scale doesn't mean degenerate
        %      DEGENERATE checking is a BUG, remove this check

        for i=1:size(model,3),
            for j=1:size(model,2),
                    
                    % x1(1,i) = (H(1,:)*X1(:,i))/(H(3,:)*X1(:,i));
                    % x1(2,i) = (H(2,:)*X1(:,i))/(H(3,:)*X1(:,i));
                    
                    X1 = [model(1,j,i) model(2,j,i) 1]';
                    
%                     if (H(3,:)*X1(:,1) < degenThres),  % if degenerating
%                         error('Homo Degenerate!!');
%                         y = 0;
%                         return;
%                     else
                        sol(1,j,i) = (H(1,:)*X1(:,1))/(H(3,:)*X1(:,1));
                        sol(2,j,i) = (H(2,:)*X1(:,1))/(H(3,:)*X1(:,1));
%                     end
                    
%                     sol{i}(k,1,j) = H(1,1)*model{i}(k,1,j) + H(1,2)*model{i}(k,2,j) + H(1,3);
%                     sol{i}(k,2,j) = H(2,1)*model{i}(k,1,j) + H(2,2)*model{i}(k,2,j) + H(2,3);
            end
        end
        
        y = sol;
 end